'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const autoprefixer = require("autoprefixer")
const IS_PROD = ['production'].includes(process.env.NODE_ENV);
const CSS_BROWSERS = ['last 10 Chrome versions', 'last 5 Firefox versions', 'Safari >= 6', 'ie> 8']
function resolve(dir) {
  return path.join(__dirname, dir)
}

const name = defaultSettings.title || '睿游网络' // page title

// If your port is set to 80,
// use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
// You can change the port by the following methods:
// port = 9528 npm run dev OR npm run dev --port = 9528
const port = process.env.port || process.env.npm_config_port || 9528 // dev port

// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
  /**
   * You will need to set publicPath if you plan to deploy your site under a sub path,
   * for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
   * then publicPath should be set to "/bar/".
   * In most cases please use '/' !!!
   * Detail: https://cli.vuejs.org/config/#publicpath
   */
  publicPath: process.env.NODE_ENV === 'production' ? '/ruiyouAdmin/' : '/', // 公共路径,
  outputDir: 'dist',
  assetsDir: 'static',
  lintOnSave: process.env.NODE_ENV === 'development',
  productionSourceMap: !IS_PROD,
  devServer: {
    port: port,
    open: true,
    hotOnly: true, // 热更新
    overlay: {
      warnings: false,
      errors: true
    },
    proxy: {
      '/api': {
        // /api 的意义在于，声明axios中url已/api开头的请求都适用于该规则，
        // 注意是以/api开头，即：axios.post({url: '/api/xxx/xxx'})
        target: 'http://106.15.74.171',  //正式生产环境
        changeOrigin: true,              //是否跨域
        pathRewrite: { '^/api': '/' }

      }
    },
    before: require('./mock/mock-server.js')
  },
  css: {
    // 启用 CSS modules
    // modules: false,
    // 是否使用css分离插件
    extract: true,
    // 开启 CSS source maps，一般不建议开启
    sourceMap: false,
    // css预设器配置项

  },
  // configureWebpack: (config) => {
  //   config.module.rules.push({
  //     //处理jquery
  //     test: require.resolve('jquery'),
  //     use: [{
  //       loader: 'expose-loader',
  //       options: 'jquery'
  //     }, {
  //       loader: 'expose-loader',
  //       options: '$'
  //     }, {
  //       loader: 'expose-loader',
  //       options: 'jQuery'
  //     }]
  //   })
  // },
  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    name: name,
    resolve: {
      alias: {
        '@': resolve('src')
      }
    },
    // plugins: [
    //   new MiniCssExtractPlugin({
    //     filename: 'css/[name].css', //这里配置跟output写法一致
    //     chunkFilename: 'css/[id][chunkhash:8].css',
    //   }),
    // ],
    // module: {
    //   rules: [
    //     {
    //       test: /\.css$/,
    //       use: [
    //         MiniCssExtractPlugin.loader,
    //         { loader: "css-loader" }
    //       ]
    //     },
    //     {
    //       test: /\.less$/,
    //       use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'less-loader']

    //     },
    //     {
    //       test: /\.s(c|a)ss$/,
    //       use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'sass-loader']
    //     },
    //     // 配置的是用来解析.css文件的loader(style-loader和css-loader)
    //   ]
    //   //   {
    //   //     // 用正则匹配当前访问的文件的后缀名是  .css
    //   //     // test: /\.css$/,
    //   //     //调用顺序是从右到左以管道的方式调用   css-loader将css文件进行解析  style-loader将解析结果放到html中，并使其生效
    //   //     test: /\.(css)$/,//同时处理css/scss
    //   //     use: [
    //   //       {
    //   //         loader: MiniCssExtractPlugin.loader,
    //   //       },
    //   //       "css-loader", //css处理器
    //   //       {
    //   //         loader: 'postcss-loader',
    //   //         /*
    //   //           postcss 这个插件的作用在于，与已有的工具集成一起使用，很少有单独使用的情况，
    //   //           通用我们用的最多的，是配合 autoprefixer 来添加各浏览器的前缀，以达到更好的兼容，
    //   //           再深入一些就是 cssnext 就是允许开发者自定义属性和变量 ：     color:var(--theme-color,#42b983);
    //   //         */
    //   //         options: {
    //   //           plugins: [
    //   //             require('autoprefixer')({
    //   //               browsers: CSS_BROWSERS,
    //   //             }),
    //   //           ],
    //   //         },
    //   //       },
    //   //       "sass-loader", //sass处理器 、甚至还可以再加一个less的处理器
    //   //       "less-loader"
    //   //     ] // webpack底层调用这些包的顺序是从右到左
    //   //     // use: ['style-loader', 'css-loader'] // webpack底层调用这些包的顺序是从右到左
    //   //   },
    //   // 

    // }

  },

  chainWebpack(config) {
    console.dir('config', config)
    // it can improve the speed of the first screen, it is recommended to turn on preload
    config.plugin('preload').tap(() => [
      {
        rel: 'preload',
        // to ignore runtime.js
        // https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/config/app.js#L171
        fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
        include: 'initial'
      }
    ])

    // when there are many pages, it will cause too many meaningless requests
    config.plugins.delete('prefetch')
    //mini-css-extract-plugin  编译打包
    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    config
      .when(process.env.NODE_ENV !== 'development',
        config => {
          config
            .plugin('ScriptExtHtmlWebpackPlugin')
            .after('html')
            .use('script-ext-html-webpack-plugin', [{
              // `runtime` must same as runtimeChunk name. default is `runtime`
              inline: /runtime\..*\.js$/
            }])
            .end()
          config
            .optimization.splitChunks({
              chunks: 'all',
              cacheGroups: {
                libs: {
                  name: 'chunk-libs',
                  test: /[\\/]node_modules[\\/]/,
                  priority: 10,
                  chunks: 'initial' // only package third parties that are initially dependent
                },
                elementUI: {
                  name: 'chunk-elementUI', // split elementUI into a single package
                  priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                  test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
                },
                commons: {
                  name: 'chunk-commons',
                  test: resolve('src/components'), // can customize your rules
                  minChunks: 3, //  minimum common number
                  priority: 5,
                  reuseExistingChunk: true
                }
              }
            })
          // https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
          config.optimization.runtimeChunk('single')
        }
      )
  }
}
